/**
 * 操作项目购买信息处理模块
 */
const Sequelize = require('sequelize')
const Op = Sequelize.Op
const sequelize = require('../db/dbconfig')
const ProjectUserBuyinfoModel = require('../db/models/project_user_buyInfo')
const ProjectModel = require('../db/models/project_infos')
const UserModel = require('../db/models/users')
const url = require("url");
const fs = require("querystring");
const projectBuyInfo = ProjectUserBuyinfoModel(sequelize)
const projectModel = ProjectModel(sequelize)
const userModel = UserModel(sequelize)
// 根据项目id和用户id检测是否已购买
exports.postProIdUserIdToBy = async (req, res) => {
  try {
    const pro_id = req.body.proId;
    const user_id = req.body.userId;
    let results = await projectBuyInfo.findOne({
      where: {
        pro_id: pro_id,
        user_id: user_id,
      },
    })
    return res.myMsg(results, 200)
  } catch (e) {
    return res.myMsg(e)
  }
}

// 添加购买信息
exports.postProIdToBuy = async (req, res) => {
  try {
    const pro_id = JSON.parse(req.body.proId);
    const { userId, username } = JSON.parse(req.body.userInfo);
    // 1. 判断是否已经购买
    let is_exist = await projectBuyInfo.findOne({
      where: {
        pro_id: pro_id,
        user_id: userId,
      },
    })
    if (is_exist) return res.myMsg('错误! 已购买该项目!', 400)
    // 2. 根据pro_id查项目价格
    let pro_price = await projectModel.findOne({
      attributes: ['price'],
      where: {
        pro_id: pro_id,
      },
    })
    // return res.myMsg(result_pro, 200)
    // 3. 根据user_id查用户money
    let user_money = await userModel.findOne({
      attributes: ['money'],
      where: {
        user_id: userId,
      },
    })
    // return res.myMsg(user_money, 200)
    // 4. 判断用户是否有足够money支付
    if (user_money < pro_price) { return res.myMSG('支付失败! 没有足够余额!', 500) }
    // 5. 扣除用户响应money
    else {
      let money = parseFloat(user_money.money) - parseFloat(pro_price.price);
      let result_userinfo = await userModel.update({
        money: money
      }, {
        where: {
          user_id: userId,
        }
      })
      // return res.myMsg(result_userinfo, 200) // [1]
      if (result_userinfo[0] !== 1 && result_userinfo[0] !== 0 ) return res.myMsg('购买失败! 服务器内部错误!', 500)
    }
    // 6. 返回支付结果
    let results = await projectBuyInfo.create({
      user_id: userId,
      pro_id: pro_id,
      user_name: username
    })
    if (!results) return res.myMsg('服务器内部错误，购买失败', 500)
    return res.myMsg(results, 200)
  } catch (e) {
    return res.myMsg(e)
  }
}